package com.stars.easyms.redis.interceptor;

import com.stars.easyms.redis.annotion.RedisExpire;
import com.stars.easyms.redis.exception.RedisInterceptorException;
import com.stars.easyms.base.util.TimeUtil;
import org.aopalliance.intercept.MethodInvocation;

import java.util.concurrent.TimeUnit;

/**
 * <p>className: RedisExpireInterceptor</p>
 * <p>description: RedisExpire注解拦截器</p>
 *
 * @author guoguifang
 * @version 1.2.1
 * @date 2019-03-18 14:25
 */
public class RedisExpireInterceptor extends AbstractRedisInterceptor<RedisExpire> {

    @Override
    protected Object invoke(MethodInvocation methodInvocation, RedisExpire redisExpire) throws RedisInterceptorException {
        Long expire = getExpire(methodInvocation);
        expire = expire != null ? expire : (Long) proceed(methodInvocation);
        if (isEnabled()) {
            if (expire == null || expire <= 0) {
                expire = TimeUtil.parseToMilliseconds(redisExpire.expire());
            }
            if (expire != null && expire > 0) {
                String redisKey = getRedisKey(methodInvocation, redisExpire.group());
                if (redisExpire.resetExpire() || easyMsRedisTemplate.getExpire(redisKey, TimeUnit.MILLISECONDS) <= 0) {
                    easyMsRedisTemplate.expire(redisKey, expire, TimeUnit.MILLISECONDS);
                }
            }
        }
        return expire;
    }

}